package com.web.filemanage.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.web.common.controller.BaseController;
import com.web.common.po.FileInfo;
import com.web.common.utils.FileUtils;
import com.web.common.utils.RandNum;
import com.web.filemanage.service.IFileService;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController{
	
	public static final String FILE_LIST = "FILE_LIST";
	
	@Resource
	private IFileService fileService;
	
	@RequestMapping(value="/doUpload",method=RequestMethod.POST)
	public String upload(HttpServletRequest request, @RequestParam("file")MultipartFile file){
		if (!file.isEmpty()) {
            log.info("上传文件"+file.getOriginalFilename());
        }
		else{
			return "/filemanage/uploadFail";
		}
		
        try {
        	String realPath = request.getSession().getServletContext().getRealPath("/");
        	String newName  = System.currentTimeMillis()+"-"+RandNum.randNum(4)+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        	
        	boolean rs = FileUtils.copyInputStreamToFile(file.getSize(), file.getInputStream(), new File(realPath+"/upload_file/",newName));
        	if(!rs){
        		return "/filemanage/uploadFail";
        	}
        	
        	FileInfo fileInfo = new FileInfo();
        	fileInfo.setFileName(file.getOriginalFilename());
        	fileInfo.setFileSize(new Long(file.getSize()).intValue());
        	fileInfo.setFileTag(0);
        	fileInfo.setFileType(0);
        	fileInfo.setFileUrl("/upload_file/"+newName);
        	
        	//保存到数据库
        	fileService.upload(fileInfo);
        	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "/filemanage/uploadFail";
		}
        return "/filemanage/uploadSuccess";
	}
	
	@RequestMapping(value="/download",method=RequestMethod.GET)
	public String download( HttpServletRequest request,HttpServletResponse response){
		
		String uid = request.getParameter("uid");
		
		FileInfo fileInfo = fileService.getInfo(uid);
		
		response.setContentType("");
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		try {
			response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileInfo.getFileName(),"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		
		try {
			InputStream inputStream = new FileInputStream(new File(realPath+fileInfo.getFileUrl()));

			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			os.flush();
			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value="/fileList",method=RequestMethod.GET)
	public String fileList(HttpServletRequest request,HttpServletResponse response){
		
		List<FileInfo> list = fileService.queryAllFile();
		request.getSession().setAttribute(FILE_LIST, list);
		return "/filemanage/fileList";
	}

	
	
}
